/**
 * 订单数据种子脚本
 * 用于创建测试订单数据
 */

const mongoose = require('mongoose');
const Order = require('../src/models/order.model');
const User = require('../src/models/user.model');
const Product = require('../src/models/product.model');
require('dotenv').config();

const MONGODB_URI = process.env.MONGODB_URI || 'mongodb+srv://2264521353:1234567890@six0.hic1spu.mongodb.net/goshop';

// 连接数据库
const connectDB = async () => {
  try {
    await mongoose.connect(MONGODB_URI, {
      dbName: 'goshop',
      serverSelectionTimeoutMS: 5000,
      socketTimeoutMS: 45000,
      family: 4
    });
    console.log('✅ 数据库连接成功');
  } catch (error) {
    console.error('❌ 数据库连接失败:', error);
    process.exit(1);
  }
};

// 生成随机订单号
const generateOrderNo = () => {
  const timestamp = Date.now().toString();
  const random = Math.random().toString(36).substring(2, 8).toUpperCase();
  return `ORD${timestamp}${random}`;
};

// 生成随机地址
const generateAddress = () => {
  const provinces = ['北京市', '上海市', '广东省', '浙江省', '江苏省', '四川省'];
  const cities = ['北京市', '上海市', '广州市', '深圳市', '杭州市', '南京市', '成都市'];
  const districts = ['朝阳区', '海淀区', '浦东新区', '黄浦区', '天河区', '福田区', '西湖区', '玄武区', '锦江区'];
  const names = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'];
  
  return {
    name: names[Math.floor(Math.random() * names.length)],
    phone: '1' + Math.floor(Math.random() * 9000000000 + 1000000000),
    province: provinces[Math.floor(Math.random() * provinces.length)],
    city: cities[Math.floor(Math.random() * cities.length)],
    district: districts[Math.floor(Math.random() * districts.length)],
    address: `测试街道${Math.floor(Math.random() * 999 + 1)}号`
  };
};

// 创建测试订单
const createTestOrders = async () => {
  try {
    console.log('🛒 开始创建测试订单...');

    // 获取测试用户
    const users = await User.find({ role: 'customer' }).limit(10);
    if (users.length === 0) {
      console.log('⚠️ 没有找到客户用户，请先创建用户数据');
      return;
    }

    // 获取测试商品
    const products = await Product.find().limit(20);
    if (products.length === 0) {
      console.log('⚠️ 没有找到商品数据，请先创建商品数据');
      return;
    }

    // 清空现有订单数据
    await Order.deleteMany({});
    console.log('🗑️ 已清空现有订单数据');

    const orderStatuses = ['待付款', '待发货', '已发货', '已完成', '已取消', '已退款', '退款中'];
    const paymentMethods = ['alipay', 'wechat', 'unionpay'];
    const testOrders = [];

    // 为每个用户创建多个订单
    for (const user of users) {
      const orderCount = Math.floor(Math.random() * 5) + 2; // 每个用户2-6个订单
      
      for (let i = 0; i < orderCount; i++) {
        const orderItemCount = Math.floor(Math.random() * 3) + 1; // 每个订单1-3个商品
        const orderItems = [];
        let itemsPrice = 0;

        // 生成订单商品
        for (let j = 0; j < orderItemCount; j++) {
          const product = products[Math.floor(Math.random() * products.length)];
          const qty = Math.floor(Math.random() * 3) + 1;
          const price = product.price;
          
          orderItems.push({
            product: product._id,
            name: product.name,
            image: product.mainImage || product.images?.[0] || '',
            price: price,
            qty: qty,
            specifications: {
              color: ['黑色', '白色', '蓝色', '红色'][Math.floor(Math.random() * 4)],
              size: ['S', 'M', 'L', 'XL'][Math.floor(Math.random() * 4)]
            }
          });
          
          itemsPrice += price * qty;
        }

        const shippingPrice = itemsPrice > 99 ? 0 : 10;
        const taxPrice = 0;
        const totalPrice = itemsPrice + shippingPrice + taxPrice;
        const status = orderStatuses[Math.floor(Math.random() * orderStatuses.length)];
        
        // 根据状态设置支付和配送状态
        const isPaid = !['待付款', '已取消'].includes(status);
        const isDelivered = ['已完成'].includes(status);
        
        const order = {
          orderNo: generateOrderNo(),
          user: user._id,
          orderItems: orderItems,
          shippingAddress: generateAddress(),
          paymentMethod: paymentMethods[Math.floor(Math.random() * paymentMethods.length)],
          itemsPrice: itemsPrice,
          taxPrice: taxPrice,
          shippingPrice: shippingPrice,
          totalPrice: totalPrice,
          isPaid: isPaid,
          paidAt: isPaid ? new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000) : null,
          isDelivered: isDelivered,
          deliveredAt: isDelivered ? new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000) : null,
          orderStatus: status,
          trackingNumber: ['已发货', '已完成'].includes(status) ? 'SF' + Math.floor(Math.random() * 1000000000000) : null,
          createdAt: new Date(Date.now() - Math.random() * 60 * 24 * 60 * 60 * 1000), // 最近60天内
          updatedAt: new Date()
        };

        testOrders.push(order);
      }
    }

    // 插入订单数据
    const createdOrders = await Order.insertMany(testOrders);
    console.log(`✅ 成功创建 ${createdOrders.length} 个测试订单`);

    // 统计各状态订单数量
    const statusStats = {};
    createdOrders.forEach(order => {
      statusStats[order.orderStatus] = (statusStats[order.orderStatus] || 0) + 1;
    });

    console.log('\n📊 订单状态统计:');
    Object.entries(statusStats).forEach(([status, count]) => {
      console.log(`  ${status}: ${count} 个`);
    });

    console.log('\n🎉 测试订单数据创建完成！');

  } catch (error) {
    console.error('❌ 创建测试订单失败:', error);
  }
};

// 主函数
const main = async () => {
  await connectDB();
  await createTestOrders();
  
  console.log('\n✅ 订单种子数据完成！');
  console.log('现在可以在应用中查看订单列表了。');
  
  process.exit(0);
};

// 运行脚本
main().catch(error => {
  console.error('❌ 脚本执行失败:', error);
  process.exit(1);
});
